import { Component, OnInit , ViewChild  } from '@angular/core';
import { CommonService } from '../../service/common.service'
import { StorageService } from '../../service/storage.service'
import { Router } from '@angular/router'

@Component({
  selector: 'app-recharge',
  templateUrl: './recharge.page.html',
  styleUrls: ['./recharge.page.scss'],
})
export class RechargePage implements OnInit {

  @ViewChild('avatarInput') avatarInput;

  public num:number;
  public filearr:any[] = [];
  public flag:boolean = true;
  public show:boolean = false;
  public formData:FormData
  // public flagA:boolean = false;
  

  constructor(public common:CommonService,public storage:StorageService,private router:Router) { 

  }

  ngOnInit() {
    
  }

  dealImage(base64, w) {
    // var preview = document.getElementById("uploadimg");
    var newImage = new Image();
    var quality = 0.6;    //压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute("crossOrigin", 'Anonymous');	//url为外域时需要
    var imgWidth, imgHeight;
    var that = this
    newImage.onload = function () {
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        console.log(imgWidth)
        console.log(imgHeight)
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
                canvas.width = w;
                canvas.height = w * imgHeight / imgWidth;
            } else {
                canvas.height = w;
                canvas.width = w * imgWidth / imgHeight;
            }
        } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            quality = 0.6;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句

        var newfile = that.dataURLtoFile(base64,'a'+'.png');
        that.formData.append('files', newfile );
    }
}
  dataURLtoFile(dataurl, filename) { // base64转file对象
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
  }

  changefile(e){
    // this.show = true 
    // 上传文件
    var fileList = this.avatarInput.nativeElement.files;
    
    // console.log(fileList)

    if (fileList.length > 3 || this.filearr.length+fileList.length > 3) {
      this.common.presentToast("上传图片数目不可以超过3个，请重新选择");
    }else if(fileList.length < 4 && fileList){

      // 遍历循环
      for(let i=0;i<fileList.length;i++){
        let size = fileList[i].size;//文件大小
        
        var reader = new FileReader()
        reader.readAsDataURL(fileList[i]);

        var that = this
        let index = i

        reader.onload = function(e) {
          // console.log(index)
          // console.log(e.target.result)
          if(size > 1048576){
            that.dealImage(e.target.result,400)
            // console.log(fileList)
          }else{
            // that.filearr.push(e.target.result)
            // formData.append('file', fileList[index])
          }
        };
      }

      this.aa(fileList)

    }
  }


  aa(arr){
    var api = '/tbr/uploadImgs'
      this.common.postbody(api,this.formData).then((response:any)=>{
        console.log(response)
        // debugger
        // 加入数组
        if(response.code == 200){
          for(var i=0;i<arr.length;i++){
            this.filearr.push(response.data[i])
          }
          this.common.presentToast("上传成功")
          // 取消上传图
          if(this.filearr.length == 3){
            this.flag = false
          }
          this.show = false
        }else{
          this.show = false
        }
        // console.log(this.filearr)
      })
  }
  changePhoto(e) {
    // 触发上传图片按钮
    this.avatarInput.nativeElement.dispatchEvent(new MouseEvent("click"))
  }

  // 确认充值
  confirm(){
    // this.router.navigate(['/confirmorder/yes'],{
    //   queryParams: {
    //     title:"充值申请提交成功",
    //     coin:this.num,
    //     url:'/home/mymoney/payhistory'
    //   }
    // })
    if(this.num == null){
      this.common.presentAlert("请输入金额")
      return false
    }
    if(this.filearr.length == 0){
      this.common.presentAlert("请上传凭证")
      return false
    }
    this.show = true
    var path = '';
    for(var i=0;i<this.filearr.length;i++){
      if(i == this.filearr.length-1){
        path += this.filearr[i]
      }else{
        path += this.filearr[i]+','
      }
      
    }
    var api="/tbr/offlineRecharge";
    var params = {
      userId:this.storage.get('PersonalInfo').userId,
      balance:this.num.toFixed(2),
      voucherPath:path
    }
    this.common.post(api,params,false).then((res:any)=>{
      console.log(res)
      if(res.code == 200){
        this.show = false
        this.router.navigate(['/success'],{
          queryParams: {
            title:"充值申请提交成功",
            coin:this.num,
            url:'/tabs/tab3'
          }
        })
      }else{
        this.show = false
      }
    })

  }




}
